package com.example.administrator.wallet.view.activity.finds.kkbank;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.KKBankCoinAdapter;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.AddProceedBean;
import com.example.administrator.wallet.model.bean.BankPrepareBean;
import com.example.administrator.wallet.model.bean.BankPrepareBtcBean;
import com.example.administrator.wallet.utils.AESUtils;
import com.example.administrator.wallet.utils.ListDataSave;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.Transaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ExtendedKey;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ValidationException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip39.SeedCalculator;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.AddressIndex;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.BIP44;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.CoinPairDerive;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BTCTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitcoinException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.CallTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.HexUtils;
import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.administrator.wallet.view.activity.asset.RecordActivity.addr;
import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.BitcoinTest;

public class CashWithdrawalOrRechargeActivity extends AppCompatActivity {

    private RelativeLayout rl_sign_re,rl_sign_ca;
    private TextView tv_Recharge_amount,tv_Current_balance,tv_TranstionFee,mV_title;
    private EditText ed_Recharge_amount;
    private Button bt_Recharge_amount,bt_Statement_of_receipt,bt_submit;
    private ImageButton bt_back;

    IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    public KKBankCoinAdapter adapter;//KKBankCoinAdapter
    private BankPrepareBean bankPrepareBean;
    private BankPrepareBtcBean bankPrepareBtcBean;
    private List<Double> unspend;
    private BTCTransaction.Input[] inputs;
    private long realOut;

    private AddProceedBean addProceedBean;

    private String title;
    private String Currency;
    private String toaddr;
    private String Raw,raw;
    private String amount;
    private String gas_price;
    private String available;

    private BitCoinECKeyPair parse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cash_withdrawal_or_recharge);

        setStatuColor();

        mV_title = (TextView)findViewById(R.id.view_title);
        bt_back = (ImageButton)findViewById(R.id.finish_img);
        rl_sign_re = (RelativeLayout)findViewById(R.id.rl_sign_re);
        rl_sign_ca = (RelativeLayout)findViewById(R.id.rl_sign_ca);
        tv_Recharge_amount = (TextView)findViewById(R.id.tv_Recharge_amount);
        ed_Recharge_amount = (EditText)findViewById(R.id.ed_Recharge_amount);
        bt_Recharge_amount = (Button) findViewById(R.id.bt_Recharge_amount);
        tv_Current_balance = (TextView) findViewById(R.id.tv_Current_balance);//当前余额+币种
        tv_TranstionFee = (TextView)findViewById(R.id.tv_TranstionFee);//矿工费
        bt_Statement_of_receipt = (Button) findViewById(R.id.bt_Statement_of_receipt);//到账说明
        bt_submit = (Button) findViewById(R.id.bt_submit);
        bt_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.KKbank);

        title = getIntent().getStringExtra("title");
        Currency = getIntent().getStringExtra("Currency");
        available = getIntent().getStringExtra("available");
        toaddr = getIntent().getStringExtra("addr");

        unspend = new ArrayList<>();

        if ("BTC".equals(Currency) | "USDT".equals(Currency)){
            //Exchange-LH-08.充值前准备（BTC/USDT）
            reqequestManager.httpPost(Api.BaseUrl + Api.Bank_Prepare_BTC, Api.getBankPrepareBTC_USDT(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null),Currency,SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "BTCaddr","")), new IRequestCallback() {
                @Override
                public void onSuccess(String Response) {
                    Gson gson = new Gson();
                    bankPrepareBtcBean = gson.fromJson(Response, BankPrepareBtcBean.class);
                    if (bankPrepareBtcBean.getCode() == 200) {
                    }
                }
                @Override
                public void onFailure(String error) {
                }
            });

        }else if ("ETH".equals(Currency)){
            //Exchange-LH-08.充值前准备（ETH）
            reqequestManager.httpPost(Api.BaseUrl + Api.Bank_Prepare_ETH, Api.getBankPrepareETH(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null),Currency,SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "ETHaddr","")), new IRequestCallback() {
                @Override
                public void onSuccess(String Response) {
                    Gson gson = new Gson();
                    bankPrepareBean = gson.fromJson(Response, BankPrepareBean.class);
                    if (bankPrepareBean.getCode() == 200) {
                    }
                }
                @Override
                public void onFailure(String error) {
                }
            });
        }
        if (title.equals(String.valueOf(R.string.Cash_withdrawal))){
            //提现
            rl_sign_ca.setVisibility(View.VISIBLE);
            rl_sign_re.setVisibility(View.GONE);
            tv_Recharge_amount.setText(R.string.Amount_withdrawn);
            ed_Recharge_amount.setHint(getString(R.string.Minimum_cash_withdrawal_amount).toString() + Currency );
            bt_Recharge_amount.setText(R.string.Full_cash_withdrawal);
            bt_submit.setText(R.string.transfer_out);
            tv_Current_balance.setText(available + Currency);

        }else if(title.equals(String.valueOf(R.string.recharge))){
            //充值
            rl_sign_ca.setVisibility(View.GONE);
            rl_sign_re.setVisibility(View.VISIBLE);
            tv_Recharge_amount.setText(R.string.Recharge_amount);
            ed_Recharge_amount.setHint(getString(R.string.Minimum_recharge_amount).toString() + Currency );
            bt_Recharge_amount.setText(R.string.Full_recharge);
            bt_submit.setText(R.string.recharge);
            tv_Current_balance.setText(available + Currency);

        }
        bt_Statement_of_receipt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),StatementOfReceiptActivity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });
        bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //充值，提现
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(title.equals(String.valueOf(R.string.Cash_withdrawal))){
                    //提现
                    String Currencyaddr = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", Currency+"addr", null);
                    reqequestManager.httpPost(Api.BaseUrl + Api.Bank_Turn_Out, Api.getBankTurnOut(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null),Currency,Currencyaddr,ed_Recharge_amount.getText().toString().trim()), new IRequestCallback() {
                        @Override
                        public void onSuccess(String Response) {
                            Gson gson = new Gson();
                            addProceedBean = gson.fromJson(Response, AddProceedBean.class);
                            if (addProceedBean.getCode() == 200) {
                                Toast.makeText(getApplicationContext(),R.string.Extraction_successful,Toast.LENGTH_SHORT).show();
                                onBackPressed();
                            }else{
                                Toast.makeText(getApplicationContext(),addProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        }
                        @Override
                        public void onFailure(String error) {
                            Toast.makeText(getApplicationContext(),error,Toast.LENGTH_SHORT).show();
                        }
                    });
                }else if(title.equals(String.valueOf(R.string.recharge))){
                    //开始充值
                    if ("BTC".equals(Currency) | "USDT".equals(Currency)){
                        BTCsendTransaction(bankPrepareBtcBean);
//                        //Exchange-LH-09.开始充值（BTC|USDT）
                        String fromaddr = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", Currency+"addr","");
                        String input = inputs.toString();
                        String value = ed_Recharge_amount.getText().toString().trim();
                        String iFee = bankPrepareBtcBean.getData().getCurrent();
                        reqequestManager.httpPost(Api.BaseUrl + Api.Bank_Send_BTC_USDT, Api.getBankSendBTC_USDT(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null),Currency,fromaddr,bankPrepareBtcBean.getData().getBank_addr(),input, value, iFee, "", Raw), new IRequestCallback() {
                            @Override
                            public void onSuccess(String Response) {
                                Gson gson = new Gson();
                                addProceedBean = gson.fromJson(Response, AddProceedBean.class);
                                if (addProceedBean.getCode() == 200) {
                                    Toast.makeText(getApplicationContext(),R.string.Recharge_successful,Toast.LENGTH_SHORT).show();
                                    onBackPressed();
                                }else{
                                    Toast.makeText(getApplicationContext(),bankPrepareBean.getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onFailure(String error) {
                                Toast.makeText(getApplicationContext(),error,Toast.LENGTH_SHORT).show();
                            }
                        });

                    }else if ("ETH".equals(Currency)){
                        ShouPopup(bankPrepareBean);
                        //Exchange-LH-09.开始充值（ETH）
                        String a = raw;
                        Log.e("CashWithdrawalOrRechargeActivity","raw = "+ raw);
                        String fromETHaddr = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "ETHaddr","");
                        Log.e("CashWithdrawalOrRechargeActivity","toaddr = "+ fromETHaddr);
                        long gasPrice = Long.valueOf(gas_price);
                        String gasprice =  "0x" + Integer.toHexString((int) gasPrice);
                        Log.e("CashWithdrawalOrRechargeActivity",SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null));
                        reqequestManager.httpPost(Api.BaseUrl + Api.Bank_Send_ETH, Api.getBankSendETH(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "token", null),Currency,fromETHaddr,toaddr,ed_Recharge_amount.getText().toString().trim(),gasprice,bankPrepareBean.getData().getGas(),bankPrepareBean.getData().getNonce(),"","0x"+ raw), new IRequestCallback() {
                            @Override
                            public void onSuccess(String Response) {
                                Gson gson = new Gson();
                                bankPrepareBean = gson.fromJson(Response, BankPrepareBean.class);
                                if (bankPrepareBean.getCode() == 200) {
                                Toast.makeText(getApplicationContext(),R.string.Recharge_successful,Toast.LENGTH_SHORT).show();
                                    onBackPressed();
                                }else{
                                    Toast.makeText(getApplicationContext(),bankPrepareBean.getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onFailure(String error) {
                                Toast.makeText(getApplicationContext(),error,Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        });

    }

    //ETH充值
    private void ShouPopup(final BankPrepareBean bankPrepareBean) {
        Double coinCounts = Double.valueOf(ed_Recharge_amount.getText().toString());
        double pow = 1 * Math.pow(10.0D, 18.0D);
        amount = String.valueOf((long) ((coinCounts) * pow));
        String gasLimit = String.valueOf(Integer.valueOf(bankPrepareBean.getData().getGas().substring(2), 16));
        Double mPrice = Double.valueOf((bankPrepareBean.getData().getCurrent()));
        Double mGas = Double.valueOf(gasLimit);
        gas_price = String.valueOf((long) (mPrice/ mGas * pow));
        String nonce = String.valueOf(Integer.valueOf(bankPrepareBean.getData().getNonce().substring(2), 16));
        String toAddr = bankPrepareBean.getData().getBank_addr().substring(2);
        byte[] rawHash;


        String eth_privateKey = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "eth_private", "eth");
        String secretKey = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", "secretKey", "secretKey");
        String eth_key = AESUtils.decrypt(eth_privateKey, secretKey);
        EthECKeyPair ecKeyPair = new EthECKeyPair(new BigInteger(eth_key, 16));
        String address = ecKeyPair.getAddress();
        //如果是eth
        if(bankPrepareBean.getData().getCoin_symbol().equals("ETH")){
            EthTransaction ethTransaction
                    = EthTransaction.create(toAddr,
                    new BigInteger(amount),
                    new BigInteger(nonce),
                    new BigInteger(gas_price),
                    new BigInteger(gasLimit),
                    3);

            Log.e("TAG", address);
            try {
                ethTransaction.sign(ecKeyPair);
            } catch (ValidationException e) {
                e.printStackTrace();
            }
            rawHash = ethTransaction.getEncoded();
        }else{
            //如果是toke  代币
            if(StringUtils.isEmpty(addr.getRam_token_addr())){
                String data_error = getResources().getString(R.string.loadData_error);
                ToastUtils.showShort(data_error);
                return;
            }
            String token_addr=addr.getRam_token_addr().substring(2);

            CallTransaction.Function function = CallTransaction.Function.fromSignature("transfer", "address","uint256");
            Transaction txConst = CallTransaction.createCallTransaction(
                    new BigInteger(nonce),
                    new BigInteger(gas_price),
                    new BigInteger(gasLimit),
                    token_addr,
                    new BigInteger("0"),
                    function,
                    toAddr,
                    new BigInteger(amount)
            );
            try {
                txConst.sign(ecKeyPair);
            } catch (ValidationException e) {
                e.printStackTrace();
            }

            rawHash = txConst.getSignBytes();
        }
        raw = HexUtils.toHex(rawHash);
        Log.e("TAG", raw);
    }

    private void BTCsendTransaction(final BankPrepareBtcBean bankPrepareBtcBean) {
//        mAddr = address.getText().toString().trim();
//        mCounts = ed_Recharge_amount.getText().toString().trim();
//        beizhu = editText.getText().toString().trim();
        if ("".equals(ed_Recharge_amount.getText().toString().trim())) {
        Toast.makeText(getApplicationContext(),"金额不能为空!",Toast.LENGTH_SHORT).show();
        }else{
            BTCShouPopup(bankPrepareBtcBean);
        }
    }

    //BTC充值
    private void BTCShouPopup(final BankPrepareBtcBean bankPrepareBtcBean) {
        try {
            //获取BTCKeyPair
            ListDataSave wallet = new ListDataSave(CashWithdrawalOrRechargeActivity.this, "wallet");
            List<String> zhujici = wallet.getDataList("zhujici");

            byte[] seed = new SeedCalculator().calculateSeed(zhujici, "");
            try {
                ExtendedKey extendedKey = ExtendedKey.create(seed);
                AddressIndex index_Bitcoin = BIP44.m().purpose44()
                        .coinType(BitcoinTest)
                        .account(0)
                        .external()
                        .address(0);
                CoinPairDerive pairDerive = new CoinPairDerive(extendedKey);
                parse = (BitCoinECKeyPair) pairDerive.derive(index_Bitcoin);
            } catch (ValidationException e) {
                e.printStackTrace();
            }

            //生成BTC交易
            //这里根据后台返回的未花费条目 自己挑选出最合适的条目作为此次转账非花费
            if (bankPrepareBtcBean.getData().getUnspent() == null) {
                Toast.makeText(CashWithdrawalOrRechargeActivity.this, R.string.transcation_error, Toast.LENGTH_SHORT).show();
            } else {
                Double total = 0.0;//该次交易总输入

                double fee = Double.valueOf(bankPrepareBtcBean.getData().getCurrent());//矿工费 通过滑动条获得
                double out = Double.valueOf(ed_Recharge_amount.getText().toString());//转出币

                double all_coin = fee + out;

                unspend.clear();
                int unsp_size = bankPrepareBtcBean.getData().getUnspent().size();
                Double[] unsp = new Double[unsp_size];

                for (int i = 0; i < bankPrepareBtcBean.getData().getUnspent().size(); i++) {
                    unsp[i] = Double.valueOf(bankPrepareBtcBean.getData().getUnspent().get(i).getValue_dec());
                }

                Arrays.sort(unsp);

                for (int i = 0; i < unsp.length; i++) {
                    total += unsp[i];
                    unspend.add(unsp[i]);
                    if (total > all_coin) {
                        break;
                    }
                }

                String myAddr = SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", Currency+"addr","");
                inputs = new BTCTransaction.Input[unspend.size()];
                for (int i = 0; i < unspend.size(); i++) {
                    Double myUnsp = unspend.get(i);
                    for (int j = 0; j < bankPrepareBtcBean.getData().getUnspent().size(); j++) {
                        BankPrepareBtcBean.DataBean.UnspentBean unspentBean = bankPrepareBtcBean.getData().getUnspent().get(j);
                        Double unsp_valueDec = Double.valueOf(unspentBean.getValue_dec());
                        if (myUnsp.equals(unsp_valueDec)) {
                            BTCTransaction.OutPoint outPoint = new BTCTransaction.OutPoint(HexUtils.fromHex(unspentBean.getTxid()), Integer.parseInt(unspentBean.getTx_output_n()));
                            inputs[i] = new BTCTransaction.Input(outPoint, BTCTransaction.Script.buildOutput(myAddr), 0xffffffff);
                        }
                    }
                }

                //String txid = "7b5a888f7c956531aa3022aaef12f09ae4b1ef554849d324bfe1193c6cd1e754";
                //BTCTransaction.OutPoint outPoint = new BTCTransaction.OutPoint(HexUtils.fromHex(txid), 0);

                BTCTransaction.Output[] outputs = new BTCTransaction.Output[2];

                //double out = Double.parseDouble(counts.getText().toString().trim());
                realOut = (long) (out * 1e8);

                double zhaoling = total - out - fee;
                long realZhaoling = (long) (zhaoling * 1e8);

                BTCTransaction.Output output1 = new BTCTransaction.Output(realOut, BTCTransaction.Script.buildOutput(bankPrepareBtcBean.getData().getBank_addr()));
                outputs[0] = output1;//收款 1
                BTCTransaction.Output output2 = new BTCTransaction.Output(realZhaoling, BTCTransaction.Script.buildOutput(SharedPrefsUtil.getValue(CashWithdrawalOrRechargeActivity.this, "wallet", Currency+"addr","")));
                outputs[1] = output2;//找零
                BTCTransaction transaction = new BTCTransaction(inputs, outputs, 0);
                byte[] sign = transaction.sign(parse);
                Raw = HexUtils.toHex(sign);
                Log.e("TAG", Raw);
            }
        } catch (BitcoinException e) {
            e.printStackTrace();
        } catch (ValidationException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);
    }
    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
